using System;
using System.Windows;

namespace DesktopWidgetApp.UI
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // 初始化应用程序
            InitializeApp();
        }

        /// <summary>
        /// 初始化应用程序配置和服务
        /// </summary>
        private void InitializeApp()
        {
            try
            {
                // 配置应用程序样式
                ConfigureApplicationStyle();

                // 初始化数据库连接
                InitializeDatabase().ConfigureAwait(false);

                // 设置全局异常处理
                AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
                DispatcherUnhandledException += OnDispatcherUnhandledException;
                TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
            }
            catch (Exception ex)
            {
                MessageBox.Show("应用程序初始化失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown();
            }
        }

        /// <summary>
        /// 异步初始化数据库
        /// </summary>
        private async Task InitializeDatabase()
        {
            try
            {
                await DesktopWidgetApp.Core.Helpers.DatabaseHelper.InitializeDatabaseAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("数据库初始化失败: " + ex.Message);
                // 尝试以只读模式继续运行
            }
        }

        /// <summary>
        /// 配置应用程序样式
        /// </summary>
        private void ConfigureApplicationStyle()
        {
            // 应用程序全局样式配置
            Resources.MergedDictionaries.Add(new ResourceDictionary
            {
                // 可以在这里添加全局样式
            });
        }

        /// <summary>
        /// 处理未捕获的线程异常
        /// </summary>
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogException((Exception)e.ExceptionObject, "未捕获的线程异常");
        }

        /// <summary>
        /// 处理UI线程未捕获异常
        /// </summary>
        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogException(e.Exception, "UI线程未捕获异常");
            e.Handled = true;
        }

        /// <summary>
        /// 处理未观察到的任务异常
        /// </summary>
        private void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            LogException(e.Exception, "未观察到的任务异常");
            e.SetObserved();
        }

        /// <summary>
        /// 记录异常信息
        /// </summary>
        private void LogException(Exception ex, string context)
        {
            try
            {
                var logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DesktopWidgetApp", "error_log.txt");
                Directory.CreateDirectory(Path.GetDirectoryName(logPath));
                
                using (var writer = new StreamWriter(logPath, true))
                {
                    writer.WriteLine("[{0}] {1}: {2}\n{3}", DateTime.Now, context, ex.Message, ex.StackTrace);
                }
                
                // 在调试模式下显示错误详情
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show($"{context}: {ex.Message}\n{ex.StackTrace}", "调试错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch { }
        }

        /// <summary>
        /// 未捕获的线程异常处理
        /// </summary>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            MessageBox.Show("应用程序发生未处理异常: " + ex?.Message, "严重错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        /// <summary>
        /// UI线程未捕获异常处理
        /// </summary>
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show("UI线程发生未处理异常: " + e.Exception.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            e.Handled = true;
        }
    }
}